<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 


class Reward_mdl extends CI_Model
{
	
	const TB_REWARD = 'cj_reward';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	
	public function get_reward_list($page = true,$limit = 0, $offset = 0, $order = 'DESC',$enabled = 0)
	{
		if($page){
			$this->db->limit(intval($limit));
			$this->db->offset(intval($offset));
			$this->db->order_by("endDate", "desc"); 
			!empty($enabled) ? $this->db->where('enabled',$enabled) : '';
			return $this->db->get(self::TB_REWARD)->result();
		}
		else {
			$reward = array();
			!empty($enabled) ? $this->db->where('enabled',1) : '';
			$this->db->order_by("endDate", "desc"); 
			$reward = $this->db->get('cj_reward')->result();
			return $reward;
		}

	}
	
	/**
	 * 根据ID取得单条信息
	 */
	public function get_reward_by_id($id)
	{
		$data = array();
		
		$this->db->select('*')->from(self::TB_REWARD)->where('id', $id)->limit(1);
		$query = $this->db->get();
		if($query->num_rows() == 1)
		{
			$data = $query->row_array();
		}
		$query->free_result();
		
		return $data;
	}
	
	/**
	 * 添加奖项
	 * @access publci
	 * @param string
	 * @return bool - true,false
	 */
	
	public function add_reward($data)
	{
		$this->db->insert(self::TB_REWARD,$data);
		return ($this->db->affected_rows() > 0) ? $this->db->insert_id() : FALSE;
	}
	
	/**
	 * 删除奖项
	 * @access publci
	 * @param int $id
	 * @return bool - true,false
	 */
	
	public function del_reward($id)
	{
		$this->db->delete(self::TB_REWARD, array('id' => $id)); 
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	
	/**
	 *修改奖项 
	 */
	public function update_reward($id,$data)
	{
		$this->db->where('id', $id);
		
		return $this->db->update(self::TB_REWARD, $data); 	
	}
	
	/**
	 * 
	 * 取得REWARD数 ...
	 * @return int num
	 */
	
	public function get_reward_count($enabled = 0)
	{
		$count = 0;
		$enabled ? $this->db->where('enabled',$enabled) : '';
		$count =  $this->db->count_all_results(self::TB_REWARD);

		return $count;
	}
	
	
	public function get_stock_num_by_productid()
	{
		$stock = $this->db->select( 'count(*) as mycount, productid, product.productname, stock.used' )
				->from( 'cj_stock as stock' )
				->join('cj_products as product', 'stock.productid=product.id' )
				->group_by( 'productid' )
				->get()
				->result_array();
		if( !empty($stock) ){
			foreach( $stock as $key => $value){
				if(!empty($value['mycount'])){
					
				}
			}
		}		
		
		return $stock;
	}
}